package com.tf_cut.backend.util;

import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Util {
	public static String genUUIDApp32(){
		UUID uuid = UUID.randomUUID(); 
		return uuid.toString().toUpperCase().replaceAll("-", "");
	}
	
	/**
	 * 得到今天日期
	 */
	public static Date getDateNow() {
		String strFormat = "yyyy-MM-dd HH:mm:ss";
		return getDateNow(strFormat);
	}

	/**
	 * 得到今天日期
	 */
	public static Date getDateNowDay() {
		String strFormat = "yyyy-MM-dd";
		return getDateNow(strFormat);
	}
	public static Date getDateNow(String pFormat) {
		SimpleDateFormat sdf = new SimpleDateFormat(pFormat);
		
		sdf.setTimeZone(TimeZone.getTimeZone("ETC/GMT-8"));
		
		try {
			return sdf.parse(sdf.format(new Date()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return new Date();
	}
	
	
	public static String formatDateToString(Date dDate){
		String strFormat = "yyyy-MM-dd";
		
		return formatDateToString(dDate,strFormat);
	}
	
	public static String formatDateToString(Date dDate,String strFormat){
		DateFormat format = new SimpleDateFormat(strFormat); 
		
		if(strFormat == null || strFormat.trim().equals("")) strFormat = "yyyy-MM-dd";
		
		return format.format(dDate);
	}
	
	public static Date formatStringToDate(String pDate) throws ParseException{
		Date dformat = new Date();
		String strFormat = "";
		
		return formatStringToDate(pDate,strFormat);
	}
	
	public static Date formatStringToDate(String pDate,String pFormatSign) throws ParseException{
		Date dFormatDate = new Date();
		String strFormat = "";
		
		if(pFormatSign == null || pFormatSign.trim().equals("")) pFormatSign ="";
		
		if(pFormatSign ==null ||pFormatSign.equals("")){
			strFormat = "yyyyMMdd";
		}
		else if(pFormatSign.equals("-")){
			strFormat = "yyyy-MM-dd";
		}
		else if(pFormatSign.equals("/")){
			strFormat = "yyyy/MM/dd";
		}
		else if(pFormatSign.equals(".")){
			strFormat = "yyyy.MM.dd";
		}
		
		return formatDate(pDate,strFormat);
	}
	
	public static Date formatDate(String pDate,String strFormat) throws ParseException{
		DateFormat format = new SimpleDateFormat(strFormat);  
		
		format.setTimeZone(TimeZone.getTimeZone("ETC/GMT-8"));
		
		Date dFormatDate = format.parse(pDate);
		
		
		return dFormatDate;
	}

	/**
	 * 格式化字符位数，不足在前补0
	 * @param ctValue	 '值'
	 * @param formatNume '位数'
	 * @return
	 */
	public static String formatValue(String ctValue, long formatNume) {
		String strValue = "";

		for (int i = ctValue.length(); i < formatNume; i++) {
			ctValue = "0" + ctValue;
		}

		return ctValue;
	}

	/**
	 * 获取'当前值'，在'当前数组集合'中的下标
	 * @param strs		'当前数组集合'
	 * @param ctValue	'当前值'
	 * @return
	 */
	public static int getCurrentIndex(String[] strs, String ctValue) {
		int ctIndex = -1;

		for (int i = 0; i < strs.length; i++) {
			if (strs[i] == null && strs[i].trim().length() == 0)
				continue;

			if (strs[i].trim().equals(ctValue.trim())) {
				ctIndex = i;
				break;
			}
		}
		return ctIndex;
	}

	/**
	 * 格式化数字位数	
	 * @param ctValue		数值
	 * @param formatNum		小数位数
	 * @return
	 */
	public static double formatNumber(double ctValue, int formatNum) {
		String str = formatNumberStr(ctValue, formatNum);

		return Double.parseDouble(str);
	}

	/**
	 * 格式化数字位数	
	 * @param ctValue		数值
	 * @param formatNum		小数位数
	 * @return	String
	 */
	public static String formatNumberStr(double ctValue, int formatNum) {

		String value = Double.toString(ctValue);
		String[] s = stringToKenizer(value.trim(), ".");
		String sv = "";

		if (s.length > 0) {
			if (formatNum > 0)
				sv = s[0] + ".";
			else
				sv = s[0];

			if (s[1].length() >= formatNum)
				sv += s[1].substring(0, formatNum);
			else {
				sv += s[1].substring(0, s[1].length());
				for (int i = s[1].length(); i < formatNum; i++) {
					sv += "0";
				}
			}
		} else {
			if (formatNum > 0)
				sv = value + ".";
			else
				sv = value;

			for (int i = 1; i < formatNum; i++) {
				sv += "0";
			}
		}

		return sv;
	}

	/**
	 * 取得分隔后值
	 * @param strVaue 值
	 * @param flag    标记
	 * @return 值数组
	 */
	public static String[] stringToKenizer(String strVaue, String flag) {
		StringTokenizer st = new StringTokenizer(strVaue, flag);

		int len = st.countTokens();
		String[] strs = new String[len];

		for (int k = 0; k < len; k++) {
			strs[k] = st.nextToken();
		}

		return strs;
	}

	/**
	 *  判断当前数组中，是否存在某对象值
	 * @param strs	   数组
	 * @param ctValue  对象值
	 * @return
	 */
	public static boolean judgeIsExist(String[] strs, String ctValue) {
		boolean bExist = false;

		for (int i = 0; i < strs.length; i++) {
			if (strs[i].trim().length() == 0)
				continue;

			if (strs[i].trim().equals(ctValue.trim())) {
				bExist = true;
				break;
			}
		}

		return bExist;
	}

	public static String getStringFromArray(String[] strData) {
		StringBuffer sbResult = new StringBuffer("");

		if (strData == null)
			return sbResult.toString();

		for (int i = 0; i < strData.length; i++) {
			if (strData[i] != null && strData[i].trim().length() > 0)
				sbResult.append(",").append(strData[i].trim());
		}
		
		if(!sbResult.toString().equals(""))
			sbResult.append(",");
		
		return sbResult.toString();
	}

	public static String getStringFromArrayWithoutPre(String[] strData) {
		StringBuffer sbResult = new StringBuffer("");

		if (strData == null)
			return sbResult.toString();

		for (int i = 0; i < strData.length; i++) {
			if (strData[i] != null && strData[i].trim().length() > 0)
				sbResult.append(",").append(strData[i].trim());
		}

		String strResult = sbResult.toString();

		if (strResult != null)
			strResult = strResult.trim();
		else
			strResult = "";

		if (strResult.startsWith(","))
			strResult = strResult.substring(1);

		return strResult;
	}

	/**
	 * 把字符串转成Long
	 * 
	 * @param val
	 * @return Long
	 */
	public static Long str2Long(String val) {
		Long value = null;
		try {
			if (val != null && !"".equals(val))

				value = Long.valueOf(val);

		} catch (Exception e) {
			// Logger.warn("把“" + val + "”从字符串转成Long型失败！");
		}
		return value;
	}

	/**
	 * 把字符串转成Double
	 * 
	 * @param val
	 * @return Double
	 */
	public static Double str2Double(String val) {
		Double value = null;
		try {

			if (val != null && !"".equals(val))
				value = Double.valueOf(val);
		} catch (Exception e) {
			// Logger.warn("把“" + val + "”从字符串转成Long型失败！");
		}
		return value;
	}

	/**
	 * 把对象转成String
	 * 
	 * @param val
	 * @return String
	 */
	public static String obj2Str(Object val) {
		String value = null;
		try {
			if (val != null && !"".equals(val))
				value = val.toString();
		} catch (Exception e) {
			// Logger.warn("把“" + val + "”从对象转成String型失败！");
		}
		return value;
	}

	/**
	 * 把字符串转成Integer
	 * 
	 * @param val
	 * @return Integer
	 */
	public static Integer str2Integer(String val) {
		Integer value = null;
		try {
			if (val != null && !"".equals(val))
				value = Integer.valueOf(val);
		} catch (Exception e) {
			// Logger.warn("把“" + val + "”从字符串转成Integer型失败！");
		}
		return value;
	}

	/**
	 * 把字符串转成Short
	 * 
	 * @param val
	 * @return Short
	 */
	public static Short str2Short(String val) {
		Short value = null;
		try {
			if (val != null && !"".equals(val))
				value = Short.valueOf(val);
		} catch (Exception e) {
			// Logger.warn("把“" + val + "”从字符串转成Long型失败！");
		}
		return value;
	}

	/**
	 * 把字符串转成Float
	 * 
	 * @param val
	 * @return Float
	 */
	public static Float str2Float(String val) {
		Float value = null;
		try {
			if (val != null && !"".equals(val))
				value = Float.valueOf(val);
		} catch (Exception e) {
			// Logger.warn("把“" + val + "”从字符串转成Long型失败！");
		}
		return value;
	}

	/**
	 * 把字符串转成Byte
	 * 
	 * @param val
	 * @return Byte
	 */
	public static Byte str2Byte(String val) {
		Byte value = null;
		try {
			if (val != null && !"".equals(val))
				value = Byte.valueOf(val);
		} catch (Exception e) {
			// Logger.warn("把“" + val + "”从字符串转成Long型失败！");
		}
		return value;
	}

	/**
	 * 對Double类型四舍五入
	 * 
	 * @param value
	 * @param num
	 *            保留几位小数
	 * @return
	 */
	public static Double rounding(Double value, int num) {
		double temp = Math.pow(10, num);
		if (value != null) {
			return new Double((Math.round(temp * value.doubleValue())) / temp);
		}
		return null;
	}

	public static double discard(double value, int num) {
		String r = Double.toString(value);
		int p = -1;
		if ((p = r.indexOf(".")) != -1 && r.length() > p + num + 1) {
			r = r.substring(0, p + num + 1);
		}
		return Double.parseDouble(r);
	}

	// 处理把全角变为半角
	public static final String SBCchange(String QJstr) {
		String outStr = "";
		String Tstr = "";
		byte[] b = null;
		if (QJstr != null) {
			QJstr = QJstr.toUpperCase();
			for (int i = 0; i < QJstr.length(); i++) {
				try {
					Tstr = QJstr.substring(i, i + 1);
					b = Tstr.getBytes("unicode");
				} catch (java.io.UnsupportedEncodingException e) {
					e.printStackTrace();
				}

				if (b[3] == -1) {
					b[2] = (byte) (b[2] + 32);
					b[3] = 0;

					try {
						outStr = outStr + new String(b, "unicode");
					} catch (java.io.UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				} else
					outStr = outStr + Tstr;
			}
		}
		return outStr.toUpperCase();
	}

	// 处理身份证15位和18位
	// 15 update to 18
	public static final String uptoeighteen(String fifteencardid) {
		String eightcardid = fifteencardid.substring(0, 6);
		eightcardid = eightcardid + "19";
		eightcardid = eightcardid + fifteencardid.substring(6, 15);
		eightcardid = eightcardid + getVerify(eightcardid);
		return eightcardid;
	}

	// 18 update to 15
	public static final String uptofifteen(String eighteencardid) {
		String fifteencardid = eighteencardid.substring(0, 6) + eighteencardid.substring(8, 17);
		return fifteencardid;
	}

	// get verify
	public static final String getVerify(String eightcardid) {

		// wi =2(n-1)(mod 11)
		int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };

		// verify digit
		int[] vi = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 };

		int[] ai = new int[18];

		int remaining = 0;
		if (eightcardid.length() == 18) {
			eightcardid = eightcardid.substring(0, 17);
		}
		if (eightcardid.length() == 17) {
			int sum = 0;
			for (int i = 0; i < 17; i++) {
				String k = eightcardid.substring(i, i + 1);
				ai[i] = Integer.parseInt(k);
			}
			for (int i = 0; i < 17; i++) {
				sum = sum + wi[i] * ai[i];
			}
			remaining = sum % 11;
		}
		return remaining == 2 ? "X" : String.valueOf(vi[remaining]);
	}

	// verify
	public static final String cardNo(String idcard) {
		String card = "";
		if (idcard.length() == 15) {
			card = uptoeighteen(idcard);
		}
		if (idcard.length() == 18) {
			card = uptofifteen(idcard);
		}
		return card;
	}

	/** 空为false*/
	public static final boolean checkNullAndEmpty(String value) {
		if (value != null && !"".equals(value)) {
			if ("".equals(value.trim()))
				return false;
			else
				return true;
		} else {
			return false;
		}
	}

	public static final String nullToEmpty(String input) {
		if (input == null) {
			return "";
		} else {
			return input;
		}
	}

	public static String getStringFromArray(String[] strData, String formattype) {
		StringBuffer sbResult = new StringBuffer("");

		if (strData == null)
			return sbResult.toString();

		for (int i = 0; i < strData.length; i++) {
			if (strData[i] != null && strData[i].trim().length() > 0)
				sbResult.append(strData[i].trim()).append(formattype);
		}
		return sbResult.toString();
	}

	
	/** 格式化sortNo，必须为3位 */
	public static String initSortNo(String sortNo, int tlen) {
		String t = "000000000000000000000000";
		if (sortNo == null) {
			return t.substring(0, tlen);
		}

		int len = sortNo.length();
		if (len == tlen) {
			return sortNo;
		} else if (len > tlen) {
			return sortNo.substring(0, tlen);
		} else if (len < tlen) {
			for (int i = 0; i < tlen - len; i++) {
				sortNo = "0" + sortNo;
			}
			return sortNo;
		}
		return t.substring(0, tlen);
	}

	public static boolean isCardNumber(String certNo) {

		if (checkNullAndEmpty(certNo)) {
			certNo = certNo.trim();
			certNo = SBCchange(certNo);
			certNo = certNo.toUpperCase();
			if (certNo.length() == 15) {
				String regEx = "(\\d{6})()?(\\d{2})(\\d{2})(\\d{2})(\\d{2})([0-9Xx])";
				Pattern pat = Pattern.compile(regEx);
				Matcher mat = pat.matcher(certNo);
				if (mat.matches()) {
					regEx = "^(\\d{2})((0([1-9]{1}))|(1[0|1|2]))(([0-2]([1-9]{1}))|(3[0|1]))";
					pat = Pattern.compile(regEx);
					mat = pat.matcher(certNo.substring(6, 12));
				}
				return mat.matches();

			} else {
				String regEx = "(\\d{6})()?(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9Xx])";
				Pattern pat = Pattern.compile(regEx);
				Matcher mat = pat.matcher(certNo);
				if (mat.matches()) {
					regEx = "^(\\d{4})((0([1-9]{1}))|(1[0|1|2]))(([0-2]([1-9]{1}))|(3[0|1]))";
					pat = Pattern.compile(regEx);
					mat = pat.matcher(certNo.substring(6, 14));
				}
				return mat.matches();
			}

		}
		return false;
	}

	/** 计算年龄
	 * 	birth -> 生日
	 *  date -> 日期 */
	public static int getAge(Date birth, Date date) {
		Calendar birthday = Calendar.getInstance();
		Calendar today = Calendar.getInstance();

		birthday.setTime(birth);
		today.setTime(date);

		int age = today.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
		today.add(Calendar.YEAR, age);
		if (birthday.after(today)) {
			age--;
		}

		if (age < 0) {
			age = 0;
		}
		return age;
	}

	/** 将数据库字段格式化为entity名字 */
	public static String strFormat(String str) {
		if (str == null || str.trim().length() == 0)
			return str;

		str = str.toLowerCase();
		String[] a = str.split("_");
		if (a != null && a.length <= 1) {
			return str;
		}

		str = a[0];
		for (int i = 1; a != null && a.length > i; i++) {
			str += a[i].substring(0, 1).toUpperCase() + a[i].substring(1, a[i].length());
		}
		return str;
	}

	/** 将element中的数据拷入到bean中 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws NoSuchMethodException */
	public static Object[] copyBeanToObject(Object fromBean, String[] params) throws Exception {
		Object[] obj = new Object[params.length];
		for (int i = 0; params != null && params.length > i; i++) {
			obj[i] = BeanUtils.getProperty(fromBean, params[i]);
		}
		return obj;
	}


	/**
	 * JDK Md5加密
	 */
	public static String md5(String target){
		StringBuilder stringBuilder = new  StringBuilder();
		MessageDigest digest = null;
		try {
			digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		byte[] digest2 = digest.digest(target.getBytes());
		for (byte b : digest2) {
			int l = b & 0xff;
			if(l<16){
				stringBuilder.append("0");
			}
			stringBuilder.append(Integer.toHexString(l));
		}
		return stringBuilder.toString();
	}
	/**
	 * 给用户密码加盐，增加安全性
	 */
	public static String getSalt(int count) {
		// 生成随机字符
		char[] str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();

		// 随机数
		Random random = new Random();

		String salt = "";
		for (int i = 0; i < count; i++) {
			salt += str[random.nextInt(str.length)];
		}
		return salt;
	}
}
